package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.Transport;
import com.scalar.chiptrack.operations.process.dao.BinSetupDAO;
import com.scalar.chiptrack.operations.process.dao.ProcessTrackDAO;
import com.scalar.chiptrack.operations.process.dao.TransportDAO;
import com.scalar.chiptrack.users.User;
 
public class TransportAction extends ChipTrackAction {
    
    public ActionForward execute (ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) 
                              throws Exception {

        int processStepID = Integer.parseInt (request.getParameter ("processStepId"));
        int oldProcessStepId = Integer.parseInt (request.getParameter ("oldProcessStepId"));
        String binSetupEnabled = (String) request.getParameter("binSetupEnabled");
        
        // added by ravikanth 
        HttpSession session = request.getSession();
 
		User user = (User)session.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			return (mapping.findForward ("login"));
		}
        //System.out.println("Track Id in TransportAction "+request.getParameter("trackId"));
		//System.out.println("Old Process Step Id  in TransportAction "+oldProcessStepId);
        
        DBTransaction dbTransaction = null;
        boolean success = false;
        
        try {
            // start transaction 
            dbTransaction = DBTransaction.getInstance();
            dbTransaction.begin();
                
            // Step 1
            // Save Transport Information
            ArrayList locations = getTransportLocations (request);
            if ((locations != null) && (locations.size() > 0)) {
                TransportDAO.saveTransportInfo (dbTransaction, processStepID, locations.iterator());
            }
            
            // Step 2
            // Update Track trables
            String comingFrom = request.getParameter ("comingFrom");
            
            if ("SORT".equalsIgnoreCase(comingFrom) == true) {
                
                int processStepId = Integer.parseInt(request.getParameter ("processStepId"));
                int trackId = Integer.parseInt (request.getParameter ("trackId"));
                String stepName = request.getParameter ("stepName");
                
                ProcessTrackDAO.updateSortAndWaferStoreTrack (dbTransaction, processStepId, trackId, stepName);
            }
            
            else if ("ASSEMBLY".equalsIgnoreCase(comingFrom) == true) {
                
                int processStepId = Integer.parseInt(request.getParameter ("processStepId"));
                int trackId = Integer.parseInt (request.getParameter ("trackId"));
                
                ProcessTrackDAO.updateAssemblyTrack (dbTransaction, processStepId, trackId);
            }
            
            else if ("WAFER_STORE".equalsIgnoreCase(comingFrom) == true) {
                
                int processStepId = Integer.parseInt(request.getParameter ("processStepId"));
                int trackId = Integer.parseInt (request.getParameter ("trackId"));
                String stepName = request.getParameter ("stepName");
                
                ProcessTrackDAO.updateSortAndWaferStoreTrack (dbTransaction, processStepId, trackId, stepName);
            }
            
            else if ("DIE_BANK".equalsIgnoreCase(comingFrom) == true) {
                
                int processStepId = Integer.parseInt(request.getParameter ("processStepId"));
                int trackId = Integer.parseInt (request.getParameter ("trackId"));
                String stepName = request.getParameter ("stepName");
                
                ProcessTrackDAO.updateSortAndWaferStoreTrack (dbTransaction, processStepId, trackId, stepName);
            }
            
            else if ("CLASS_STORE".equalsIgnoreCase(comingFrom) == true) {
                
                int processStepId = Integer.parseInt(request.getParameter ("processStepId"));
                int trackId = Integer.parseInt (request.getParameter ("trackId"));
                String stepName = request.getParameter ("stepName");
                
                ProcessTrackDAO.updateTestTrack (dbTransaction, processStepId, trackId, stepName);
            }
            
            else if ("MARK_AND_PACK".equalsIgnoreCase(comingFrom) == true) {
                
                int processStepId = Integer.parseInt(request.getParameter ("processStepId"));
                int trackId = Integer.parseInt (request.getParameter ("trackId"));
                String previousStepName = request.getParameter("previousStepName");
                String productName = request.getParameter ("productName");
                
                ProcessTrackDAO.updateMarkAndFG (dbTransaction, processStepId, trackId, previousStepName, productName, ProcessTrackDAO.MARK_AND_PACK);
            }
            
            else if (("TEST".equalsIgnoreCase(comingFrom) == true) && (binSetupEnabled.equalsIgnoreCase("false"))) {
                // Update track ID information only if BinSetup is disabled.. or else update it in BinSetup or BinSubstitute
                
                int processStepId = Integer.parseInt(request.getParameter ("processStepId"));
                int trackId = Integer.parseInt (request.getParameter ("trackId"));
                String stepName = request.getParameter ("stepName");
                ProcessTrackDAO.updateTestTrack (dbTransaction, processStepId, trackId, stepName);
            }           

            else if ("FINISHED_GOODS".equalsIgnoreCase(comingFrom) == true) {
                
                int processStepId = Integer.parseInt(request.getParameter ("processStepId"));
                int trackId = Integer.parseInt (request.getParameter ("trackId"));
                String previousStepName = request.getParameter("previousStepName");
                String productName = request.getParameter ("productName");
                
                ProcessTrackDAO.updateMarkAndFG (dbTransaction, processStepId, trackId, previousStepName, productName, ProcessTrackDAO.FG);
            }
      
            success = true;
        }
        catch (ScalarException se) {
            // Exception while saving the data..
            // log it
            se.getRootCause().printStackTrace();
        }

        finally {
            // Rollback or Commit the Transaction

            if (success == true) {
                dbTransaction.commit();
            }
            else {
                dbTransaction.rollback();
            }
        }
        
        if (success == false) {
            return (mapping.findForward ("failure"));
        }
               
        
        request.setAttribute("previousStepId", processStepID+"");
        request.setAttribute("baseProductID", request.getParameter("baseProductId"));   // for ProcessView
        
        if ((binSetupEnabled != null) && (binSetupEnabled.equalsIgnoreCase("true"))) {
        
            //HttpSession session = request.getSession();
            
            session.setAttribute ("processStepId", processStepID+"");                          //
            session.setAttribute ("oldProcessStepId", oldProcessStepId+"");                          //
            session.setAttribute ("trackId", request.getParameter("trackId"));               //  
            session.setAttribute ("stepName", request.getParameter("stepName"));             // used in Bin_Setup Action
            session.setAttribute ("baseProductId", request.getParameter("baseProductId"));  //
 	
			ArrayList binList = null;
			if (oldProcessStepId != -1) 
			{  
				binList = BinSetupDAO.loadBins (oldProcessStepId,Integer.parseInt(request.getParameter("trackId")));
			}
			else 
			{
				binList = BinSetupDAO.loadBins (processStepID,Integer.parseInt(request.getParameter("trackId")));
			}
            
            request.setAttribute ("binList", binList); 
        
            return (mapping.findForward("binsetup"));
        }
        
        return (mapping.findForward("success"));
    }
    
    
    private ArrayList getTransportLocations (HttpServletRequest request) {
        
        ArrayList transports = new ArrayList();
        
        String[] sourceLocationName = request.getParameterValues("sourceLocationName");
        if (sourceLocationName == null) {
            return null;
        }
        
        String[] sourceLocationID = request.getParameterValues ("sourceLocationID");
        String[] destLocationName = request.getParameterValues ("destLocationName");
        String[] destLocationID   = request.getParameterValues ("destLocationID");
        String[] normalCost       = request.getParameterValues ("normalCost");
        String[] normalTime       = request.getParameterValues ("normalTime");
		String[] expressCost      = request.getParameterValues ("expressCost");
		String[] expressTime      = request.getParameterValues ("expressTime");
        
        Transport transport = null;
        for (int i=0; i<sourceLocationName.length; i++) {
                
            // Proper error checking is required .. to be revisited
            try {
                // changed by hareesh on 25th August 2003
                // -- START --
               /* transport = new Transport (sourceLocationName[i],
                                        Integer.parseInt (sourceLocationID[i]),
                                        destLocationName[i],
                                        Integer.parseInt (destLocationID[i]),
                                        Integer.parseInt (normalTime[i]),
                                        Float.parseFloat(normalCost[i]),
                                        Integer.parseInt (expressTime[i]),
                                        Float.parseFloat(expressCost[i]));*/
                  transport = new Transport();
                  transport.setSourceLocationName( sourceLocationName[i] );
                  transport.setSourceLocationID( Integer.parseInt (sourceLocationID[i] ) );
                  transport.setDestinationLocationName( destLocationName[i] );
                  transport.setDestinationLocationID( Integer.parseInt ( destLocationID[i] ) );
                  transport.setNormalTime( normalTime[i] != null && normalTime[i].trim().length() != 0 ? Integer.parseInt( normalTime[i] ) : 0  );
                  transport.setNormalCost( normalCost[i] != null && normalCost[i].trim().length() != 0 ? Float.parseFloat( normalCost[i] ) : 0.0f  );
                  transport.setExpressTime( expressTime[i] != null && expressTime[i].trim().length() != 0 ? Integer.parseInt( expressTime[i] ) : 0  );
                  transport.setExpressCost( expressCost[i] != null && expressCost[i].trim().length() != 0 ? Float.parseFloat( expressCost[i] ) : 0.0f  );

                // -- END --

                transports.add (transport);
            }
            catch (NumberFormatException nfe) {
                // Invalid values..
                // nfe.printStackTrace();   
            }
        }
        
        return transports;
    }
}